package com.kikcn.demo.domain;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * User: wlai
 * Date: 4/9/15
 * Time: 15:53 PM
 */
@Entity
@Table(name = "users")
public class User extends Base implements Serializable, UserDetails {

@Column(name = "account")
private String name;
@Column
private String password;
@Column
private boolean enable;
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = {
        @JoinColumn(name = "uid", referencedColumnName = "id")
}, inverseJoinColumns = {
        @JoinColumn(name = "rid", referencedColumnName = "id")})
private Set<Role> roles;

public User() {
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
    Set<Role> roles = this.getRoles();

    for (Role role : roles) {
        authSet.add(new SimpleGrantedAuthority(role.getName()));
    }
    return authSet;
}

public String getPassword() {
    return password;
}

@Override
public String getUsername() {
    return this.getName();
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return this.enable;
}

public void setPassword(String password) {
    this.password = password;
}

public void setEnable(boolean enable) {
    this.enable = enable;
}

public Set<Role> getRoles() {
    return roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}
}
